package com.motu.monstercity.server.game.logic;

import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.CsGameSystem;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.florist.FloristSecretary;
import com.motu.monstercity.server.game.commondata.florist.FloristTask;
import com.motu.monstercity.server.game.commondata.system.SystemConstant;
import com.motu.monstercity.server.game.userdata.*;
import io.vertx.core.json.JsonArray;

import java.util.*;
import java.util.stream.Collectors;

public class FloristManager extends FloristUserData {

    public static void initFlorist(UserInfo userInfo) {
        UserFlorist userFlorist = getUserFlorist(userInfo.getId());
        initTaskList(userFlorist);
    }

    // 初始化花店任务
    public static void initTaskList(UserFlorist userFlorist) {
        long userId = userFlorist.getId();
        JsonArray taskArray = userFlorist.getTaskArray();
        boolean update = false;
        if (taskArray.size() < AllParam.FLORIST_SHOW_TASK_COUNT) { // 任务未满就加新任务
            List<FloristTask> taskList = new ArrayList<>(getFloristTaskMap().values());
            List<UserFloristTask> userFloristTaskList = getUserFloristTaskList(userId); // 已开始的任务
            Set<Integer> allTaskIds = userFloristTaskList.stream().map(UserFloristTask::getTaskId).collect(Collectors.toSet());
            taskList.sort(Comparator.comparing(FloristTask::getSort)); // 排序
            for (FloristTask task : taskList) {
                if (taskArray.contains(task.getId()) || allTaskIds.contains(task.getId())) { // 在现有任务列表或已完成的任务列表里面的就跳过
                    continue;
                }
                UserFloristTask userFloristTask = createNewTask(userId, task);
                userFloristTask.doCreate();
                taskArray.add(task.getId());
                allTaskIds.add(task.getId());
                if (taskArray.size() >= AllParam.FLORIST_SHOW_TASK_COUNT) {
                    break;
                }
            }
            userFlorist.putTask(taskArray.toString());
            update = true;
        }
        // 检测是否需要生成新任务（配置表如果新增了新任务则要刷新）
        List<UserFloristTask> userFloristTaskList = getUserFloristTaskList(userId);
        for (int i = 0; i < taskArray.size(); i++) {
            int taskId = taskArray.getInteger(i);
            Map<Integer, UserFloristTask> userFloristTaskMap = userFloristTaskList.stream().collect(Collectors.toMap(UserFloristTask::getTaskId, t -> t));
            UserFloristTask userFloristTask = userFloristTaskMap.get(taskId);
            if (userFloristTask == null) { // 未开始的任务不判断
                continue;
            }
            if (userFloristTask.getIsRecv() == 1) {
                boolean changed = completeTask(userFlorist, userFloristTask, userFloristTaskList);
                if (changed) {
                    update = true;
                }
            }
        }
        if (addNewSecretary(userFlorist)) {
            update = true;
        }
        if (update) {
            userFlorist.update();
        }
    }

    /**
     * 完成任务后，将旧任务按顺序替换下一个任务
     * @param userFlorist 花店数据（如果替换成功，则任务顺序会保存在这里）
     * @param userFloristTask 当前完成的任务
     * @param userFloristTaskList 总任务数据
     * @return 替换成功返回true，替换失败返回false
     */
    public static boolean completeTask(UserFlorist userFlorist, UserFloristTask userFloristTask, List<UserFloristTask> userFloristTaskList) {
        long userId = userFloristTask.getUserId();
        JsonArray taskArray = userFlorist.getTaskArray();
        int index = taskArray.getList().indexOf(userFloristTask.getTaskId());
        if (index < 0) {
            return false;
        }
        // 取出id最大的任务
        UserFloristTask maxTask = userFloristTaskList.stream().max(Comparator.comparing(UserFloristTask::getSort)).orElse(null);
        if (maxTask != null) {
            FloristTask nextTask = getNextFloristTask(maxTask.getTaskId());
            if (nextTask != null) {
                UserFloristTask nextUserTask = createNewTask(userId, nextTask);
                nextUserTask.doCreate();
                taskArray.set(index, nextTask.getId());
                userFlorist.putTask(taskArray.toString());
                userFloristTaskList.add(nextUserTask);
                return true;
            }
        }
        return false;
    }

    // 根据任务配置创建新任务
    public static UserFloristTask createNewTask(long userId, FloristTask task) {
        UserFloristTask userFloristTask = new UserFloristTask(userId, task.getId());
        if (task.getInherit() == 1) {
            long taskValue = MainTaskManager.getTaskValue(userId, task.getTaskType(), task.getParam());
            if (taskValue > 0) {
                userFloristTask.putCurP(taskValue);
            }
        }
        return userFloristTask;
    }

    public static List<UserFloristTask> getShowTaskList(UserFlorist userFlorist, List<UserFloristTask> allTaskList) {
        List<UserFloristTask> retList = new ArrayList<>();
        JsonArray taskIdArray = userFlorist.getTaskArray();
        Map<Integer, UserFloristTask> userFloristTaskMap = allTaskList.stream().collect(Collectors.toMap(UserFloristTask::getTaskId, t -> t));
        for (int i = 0; i < taskIdArray.size(); i++) {
            UserFloristTask task = userFloristTaskMap.get(taskIdArray.getInteger(i));
            if (task != null) {
                retList.add(task);
            }
        }
        return retList;
    }

    public static boolean addNewSecretary(UserFlorist userFlorist) {
        boolean update = false;
        JsonArray secretaryArray = userFlorist.getSecretariesArray();
        if (secretaryArray.size() < AllParam.FLORIST_SHOW_TASK_COUNT) { // 不足5个补足
            List<FloristSecretary> secretaryList = new ArrayList<>(getFloristSecretaryMap().values());
            secretaryList.sort(Comparator.comparing(FloristSecretary::getSort)); // 根据sort字段排序
            for (FloristSecretary secretary : secretaryList) {
                if (!secretaryArray.contains(secretary.getSecretaryId())) {
                    secretaryArray.add(secretary.getSecretaryId());
                    update = true;
                    if (secretaryArray.size() >= AllParam.FLORIST_SHOW_TASK_COUNT) {
                        break;
                    }
                }
            }
        }
        // 检测已完成的秘书列表，看是否有新秘书解锁
        JsonArray secretaryUnlock = userFlorist.getSecretaryUnlockArray();
        for (int i = 0; i < secretaryArray.size(); i++) {
            int secretaryId = secretaryArray.getInteger(i);
            if (!secretaryUnlock.contains(secretaryId)) { // 未解锁不移除
                continue;
            }

            // 找出排序最大的秘书
            List<Integer> secretaryList = secretaryArray.stream().toList().stream().map(e -> (Integer) e).toList();
            List<FloristSecretary> floristSecretaryList = new ArrayList<>();
            for (FloristSecretary value : getFloristSecretaryMap().values()) {
                if (secretaryList.contains(value.getSecretaryId())) {
                    floristSecretaryList.add(value);
                }
            }
            FloristSecretary maxSecretary = floristSecretaryList.stream().max(Comparator.comparing(FloristSecretary::getSort)).orElse(null);
            if (null != maxSecretary) {
                FloristSecretary nextSecretary = getNextFloristSecretary(maxSecretary.getSecretaryId());
                if (null != nextSecretary) { // 如果当前排序最大的秘书后面还有秘书则自动更新
                    int index = secretaryArray.getList().indexOf(secretaryId); // 找出要替换的下标
                    secretaryArray.set(index, nextSecretary.getSecretaryId());
                    update = true;
                }
            }
        }
        if (update) {
            userFlorist.putSecretaries(secretaryArray.toString());
        }
        return update;
    }

    public static void updateTask(Common.PBUserData.Builder pbUserData, UserInfo userInfo,  int taskType, long value, int param, boolean isAdd) {
        long userId = userInfo.getId();
        List<FloristTask> taskList = getFloristTaskListByType(taskType);
        if (taskList == null || taskList.isEmpty()) {
            return;
        }
        UserFlorist userFlorist = getUserFlorist(userId);
        JsonArray taskArray = userFlorist.getTaskArray();
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        for (int i = 0; i < taskArray.size(); i++) {
            int taskId = taskArray.getInteger(i);
            FloristTask floristTask = getFloristTask(taskId);
            if (floristTask == null || floristTask.getTaskType() != taskType || floristTask.getParam() != param) { // 如果没有配置活动或类型不匹配则跳过
                continue;
            }
            UserFloristTask userFloristTask = getUserFloristTask(userId, taskId);
            if (userFloristTask == null) {
                userFloristTask = createNewTask(userId, floristTask);
                if (floristTask.getInherit() == 0) {
                    userFloristTask.putCurP(value);
                }
                userFloristTask.doCreate();
                if (userFloristTask.getCurP() >= floristTask.getTaskPar()) { // 如果加完进度后达标目标值则下发红点
                    sendTaskRedPoint(userInfo, userExtInfo);
                }
                continue;
            }
            if (userFloristTask.getCurP() >= floristTask.getTaskPar()) { // 如果已经达到目标值则不处理
                continue;
            }
            if (isAdd) {
                userFloristTask.addCurP(value);
            } else {
                if (value > userFloristTask.getCurP()) {
                    userFloristTask.putCurP(value);
                }
            }
            userFloristTask.update();
            ProtoDataUtils.updatePBUserData(pbUserData, userFloristTask);
            if (userFloristTask.getCurP() >= floristTask.getTaskPar()) { // 如果加完进度后达标目标值则下发红点
                sendTaskRedPoint(userInfo, userExtInfo);
            }
        }
    }

    // 任务完成时下发红点
    public static void sendTaskRedPoint(UserInfo userInfo, UserExtInfo userExtInfo) {
        GameUser.sendRedPointPrompt(userInfo, userExtInfo, SystemConstant.RED_POINT_TYPE_FLORIST);
    }

    // 登录下发红点
    public static boolean checkRedPoint(UserInfo userInfo, CsGameSystem.CSGameSystemRedPointResponse.Builder response) {
        UserFlorist userFlorist = getUserFlorist(userInfo.getId());
        long userId = userInfo.getId();
        JsonArray secretaryArray = userFlorist.getSecretariesArray();
        JsonArray unlockArray = userFlorist.getSecretaryUnlockArray();
        List<Integer> lockList = new ArrayList<>(secretaryArray.stream().toList().stream().map(e -> (Integer) e).toList());
        List<Integer> unlockList = unlockArray.stream().toList().stream().map(e -> (Integer) e).toList();
        lockList.removeAll(unlockList);
        boolean hasRedpoint = false;
        CsGameSystem.RedPoint_Florist.Builder redPointBuilder = CsGameSystem.RedPoint_Florist.newBuilder();
        for (Integer secretaryId : lockList) {
            FloristSecretary secretary = getFloristSecretary(secretaryId);
            if (null != secretary) {
                if (BagManager.checkNeedItemNum(userInfo, secretary.getNeedItemList())) {
                    redPointBuilder.setSecretary(true);
                    hasRedpoint = true;
                    break;
                }
            }
        }
        List<UserFloristTask> taskList = getUserFloristTaskList(userId);
        List<UserFloristTask> unReceiveList = taskList.stream().filter(t -> !t.isReceive()).toList(); // 过滤出未点完成的任务
        for (UserFloristTask userFloristTask : unReceiveList) {
            FloristTask task = getFloristTask(userFloristTask.getTaskId());
            if (task != null && userFloristTask.getCurP() >= task.getTaskPar()) {
                redPointBuilder.setTask(true);
                hasRedpoint = true;
                break;
            }
        }
        if (hasRedpoint) {
            response.setFlorist(redPointBuilder);
//            JsonObject jsonObject = ResponseUtils.getResponseData(CmdEnum.EnumCmdID.CMD_GAME_SYSTEM_RED_POINT_VALUE, response.build().toByteArray());
//            GameUser.pushToUser(userInfo.getId(), jsonObject);
        }
        return hasRedpoint;
    }

}
